/**
 * Created by zhangyida on 15/12/29.
 */
'use strict';

import {
    Text,
    View,
    Image,
    TouchableHighlight,
    PushNotificationIOS,
    TouchableOpacity,
    RefreshControl,
    AsyncStorage,
    StyleSheet,
    LinkingIOS,
    ScrollView,
    AlertIOS,
    Navigator,
} from 'react-native';
import React from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import URL from '../config/server';
import {Utils} from '../config/utils';
import {Key} from '../config/key';

/*首页中的组件*/
import Search from '../component/Search';
import Slider from '../component/Slider';
import ItemList from '../component/ItemList';
import CopyRight from '../component/CopyRight';
import Category from '../component/Category';
import Footer from '../component/Footer';
import ScrollNews from '../component/ScrollNews';

const NavigationBarRouteMapper = {
    LeftButton(route, navigator, index, navState) {
        return null;
    },
    RightButton(route, navigator, index, navState) {
        return null;
    },
    Title(route, navigator, index, navState) {
        return (
            <Text style={styles.navTitle}>
                神秘涨停网
            </Text>
        );
    }
};

export default class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isRefreshing: false,
            value: {
                userType: ''
            },
            scroll:'',
            sliderImg: ['http://101.200.229.204/smzt/admin/login/login2.png', 'http://101.200.229.204/smzt/admin/login/login2.png', 'http://101.200.229.204/smzt/admin/login/login2.png'],
            sliderLink: ['http://www.baidu.com', 'http://www.baidu.com', 'http://www.baidu.com'],
            advSliderImg:[],
            advSliderLink:[],
            timeOut: 8,
            advHide:false,
        };
    }

    componentDidMount() {
        AsyncStorage.getItem("userType", (err, value)=> {
            if (!err && value) {
                this.setState({
                    userType: value
                })
            }
        });
        this.fetchSlider();
        this.fetchScroll();
        if (Utils.versionCheck) {
            this._checkVersion();
            Utils.versionCheck = false;
        }
    }

    componentWillMount() {
    }

    componentWillUnmount(){
        Key.showAdv = false;
    }
    _onRefresh() {
        this.setState({isRefreshing: true});
        setTimeout(() => {
            this.setState({
                isRefreshing: false
            });
        }, 2000);
    }

    _checkVersion() {
        let that = this;
        const VERSION = URL.config + 'iosversion';
        Utils.get1(VERSION, function (data) {
            if (data > Utils.version) {
                AlertIOS.alert(
                    '温馨提示',
                    '本软件已发布最新版本,为了您享受最新的服务请你尽快前往AppStore更新',
                    [
                        {
                            text: '去更新', onPress: () => {
                            that._goAppstore()
                        }
                        },
                        {text: '忽略', onPress: () => console.log('Bar Pressed!')},
                    ]
                )
            }
        });
    }

    _goAppstore() {
        const url = 'https://itunes.apple.com/us/app/shen-mi-zhang-ting-wang/id1073503577?l=zh&ls=1&mt=8';
        LinkingIOS.canOpenURL(url, (supported) => {
            if (!supported) {
                AlertIOS.alert('Can\'t handle url: ' + url);
            } else {
                LinkingIOS.openURL(url);
            }
        });
    }

    //获取滚动条数据
    fetchScroll() {
        let that = this;
        const SCROLL = URL.local + 'roll';
        Utils.get(SCROLL, function (data) {
            that.setState({
                scroll: data.content
            })
        })
    }

    toOther(value) {
        if (value == "MainPage") {
            return;
        }
        this.props.navigator.replace({
            id: value
        });
    }

    fetchSlider() {
        let that = this;
        
        const SLIDER = URL.local + 'adv/index/3';
        Utils.get(SLIDER, function (data) {
            let tempPic = [];
            let tempLink = [];
            data.forEach(function (item) {
                tempPic.push(item.image);
                tempLink.push(item.url)
            });
            that.setState({
                sliderImg: tempPic,
                sliderLink: tempLink
            })
        });
        const ADVSLIDER = URL.local+'adv/pop/3'
        Utils.get(ADVSLIDER,function (data) {
            let tempPic = [];
            let tempLink = [];
            if(data){
                data.forEach(function (item) {
                    tempPic.push(item.image);
                    tempLink.push(item.url)
                });
                that.setState({
                    advSliderImg: tempPic,
                    advSliderLink: tempLink,
                    advHide:Key.showAdv
                })    
            }
        })
    }

    _close(){
        this.setState({
            advHide:false
        })
    }


    renderScene() {
        return (
                <View style={styles.container}>
                    <ScrollView style={styles.up} refreshControl={
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={()=>{this._onRefresh()}}
                            tintColor="#ff0000"
                            title="正在刷新..."
                            colors={['#ff0000', '#00ff00', '#0000ff']}
                            progressBackgroundColor="#e02820"
                          />
                        }>
                        {
                            this.state.scroll!=''?
                            <ScrollNews content={this.state.scroll}/>:null
                        }
                        <Image
                            style={styles.mainTitle}
                            source={require('../image/main-title.png')}
                        />
                        <Search
                            userType={this.state.userType} 
                            navigator={this.props.navigator}
                            />
                        <Category
                            userType={this.state.userType} 
                            navigator={this.props.navigator}/>
                        <Slider 
                            height={125}
                            navigator={this.props.navigator}
                            sliderImg={this.state.sliderImg}
                            sliderLink={this.state.sliderLink}
                            timeOut={this.state.timeOut}/>
                        <ItemList navigator={this.props.navigator}/>
                        <CopyRight/>
                    </ScrollView>
                    {this.state.advHide?
                    <View style={styles.advSlider}>
                        <Slider 
                            height={381}
                            width={250}
                            navigator={this.props.navigator}
                            sliderImg={this.state.advSliderImg}
                            sliderLink={this.state.advSliderLink}
                            timeOut={this.state.timeOut}/>
                        <TouchableOpacity onPress={()=>this._close()}> 
                            <Icon style={styles.close} name="ios-close-circle-outline" size={34} color="#000"/>
                        </TouchableOpacity>
                    </View>:null}
                    <View style={styles.down}>
                        <Footer navigator={this.props.navigator} current={"Main"}/>
                    </View>
                </View>
                
        );
    }

    render() {
        return (
            <Navigator
                ref='main'
                navigator={this.navigator}
                renderScene={this.renderScene.bind(this)}
                navigationBar={
                  <Navigator.NavigationBar
                    style={{backgroundColor: '#e02820', alignItems: 'center'}}
                    routeMapper={NavigationBarRouteMapper} />
                }
            />
        );
    }
}

const styles = StyleSheet.create({
    navTitle: {
        flex: 1,
        justifyContent: 'center',
        color: 'white',
        fontSize: 20,
        marginTop: 10,
        alignItems: 'center'
    },
    container: {
        marginTop: 64,
        backgroundColor: '#f5f5f9',
        flex: 1
    },
    up: {
        flex: 1
    },
    down: {
        height: 44,
        backgroundColor: '#000000',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    },
    slider: {
        height: 125
    },
    mainTitle:{
        backgroundColor:'#ffffff',
        height:60,
        width: Utils.size.width,
        resizeMode: Image.resizeMode.contain
    },
    advSlider: {
        position: 'absolute',
        bottom: 150,
        width: 250,
        height: 381,
        left: Utils.size.width / 2 - 125
    }, 
    close:{
        alignSelf:'center',
        backgroundColor:'rgba(255, 255, 255, 0)'
    }
});